<?php

/**
 * 默认控制器
 */
class Controller_Behaviorlog extends Controller_Abstract
{
    /* ******************************************************************** */
    function actionOutput()
    {
        $show_box['title'] = '查询行为日志';
		$this->_view['form'] = new Form_BeSearch(url('default::behaviorlog/list'));
		//查询，导出和批量删除
        //dump($_SESSION);
    }

	function actionOutputs()
    {
        $show_box['title'] = '查询详细行为日志';
		$this->_view['form'] = new Form_BeSearch(url('default::behaviorlog/hostlist'));

		if(isset($this->_context->mac)){
			$this->_view['form']->add(QForm::ELEMENT, 'mac', array('_ui' => 'hidden','value' => $this->_context->mac));
		}

		if(isset($this->_context->id)){
			$this->_view['form']->add(QForm::ELEMENT, 'id', array('_ui' => 'hidden','value' => $this->_context->id));
		}
		//查询，导出和批量删除
        //dump($_SESSION);
    }

    /* ******************************************************************** */
    function actionIndex()
    {
        $show_box['title'] = '行为日志首页';
		$iftype='';

        if ($this->_app->currentUserRoles())
        {

			$this->_view['sk']='';

			//$this->_view['form'] = new Form_BeSearch(url('default::behaviorlog/index'));
			$this->_view['form'] = new Form_BeFliter(url('default::behaviorlog/index', array('mac' => $this->_context->mac,'startd' => $this->_context->startd,'endd' => $this->_context->endd)));

			if(isset($this->_context->mac)){
				$this->_view['form']->add(QForm::ELEMENT, 'mac', array('_ui' => 'hidden','value' => $this->_context->mac));
			}

			if(isset($this->_context->startd)){
				$this->_view['form']->add(QForm::ELEMENT, 'startdate', array('_ui' => 'hidden','value' => $this->_context->startd));
			}

			if(isset($this->_context->endd)){
				$this->_view['form']->add(QForm::ELEMENT, 'enddate', array('_ui' => 'hidden','value' => $this->_context->endd));
			}


			
			//时间筛选
			$addconds="date = '".date("Y-m-d")."'";
			$this->_view['startd']='';
			$this->_view['endd']='';
			$this->_view['macs']='';
			$addmac='';$addcontent='';
			$edit_one=array();
			if ($this->_context->isPOST())
			{
				$edit_one['infotype']=$_POST['infotype'];
				$edit_one['content']=$_POST['content'];
				$this->_view['form']->import($edit_one);
				//$this->_view['form']['infotype']=$_POST['infotype'];
				if($_POST['startdate']==$_POST['enddate']){
					$endd=$this->my_date_add('d',$_POST['enddate'],1);
				}else{
					$endd=$_POST['enddate'];
				}
				$this->_view['startd']=$_POST['startdate'];
				$this->_view['endd']=$endd;
				
				if(isset($_POST['mac'])){
					$this->_view['macs']=$_POST['mac'];
					$addmac=" and macaddress='".$_POST['mac']."' ";
				}

				

				//类型对应数据表
				if(isset($_POST['infotype'])){
					$iftype=$_POST['infotype'];

					switch ($iftype)
					{
					case '':
					  $skey='content';break;
					case 'process':
					  $skey='procname';break;
					case 'fileinfo':
					  $skey='filename';break;
					case 'tcpconns':
					  $skey='tcpconns';break;
					case 'cmdinfo':
					 $skey='detail';break;
					case 'terminallog':
					  $skey='loginip';break;
					case 'reginfo':
					  $skey='reginfo';break;
					case 'reginfo1':
					  $skey='reginfo1';break;
					default:
					  $skey='content';break;
					}
					$this->_view['sk']=$skey;

					//内容关键字
					if($_POST['content']!=''){
						$this->_view['contents']=$_POST['content'];
						$addcontent=" and ".$skey." like '%".$_POST['content']."%' ";
					}
				}else{
				
					//内容关键字
					if($_POST['content']!=''){
						$this->_view['contents']=$_POST['content'];
						$addcontent=" and content like '%".$_POST['content']."%' ";
					}

					$this->_view['sk']='';
				
				}

				//$addconds="date >='".$_POST['startdate']."' and date<='".$endd."'".$addcontent.$addmac;
				$addconds="date >='".$_POST['startdate']."' and date<='".$endd."'".$addcontent;
				//echo $this->my_date_add('d',$_POST['enddate'],1);
				//dump($addconds);
				//dump($_POST);
			}

			
			
			
			
			if($this->_context->startd !='' && $this->_context->endd !=''){
				//echo $this->_context->macs;
				
				$this->_view['startd']=$this->_context->startd;
				$this->_view['endd']=$this->_context->endd;
				
				if($this->_context->macs!=''){
					$addmac=" and macaddress='".$this->_context->macs."' ";
				}

				//$addconds="date >='".$this->_context->startd."' and date<='".$this->_context->endd."'".$addmac;
				$addconds=" (date >='".$this->_context->startd."' and date<='".$this->_context->endd."') ".$addcontent;
				
			}

			$sdstr='';$edstr='';
			if($this->_context->startd!='')
					$sdstr='&startd='.$this->_context->startd.'';

			if($this->_context->startd!='')
					$edstr='&endd='.$this->_context->endd.'';

			if($this->_context->mac==''){

				$pagesize = 10;
				// 获取当前页数，通常为get方式参数
				$page = $this->_context->page;
				$this->_view['pageno']=$page;
				
				switch ($iftype)
				{
				case '':
				  $select = OldAction::find($addconds)->limitPage($page, $pagesize);
				  break;
				case 'process':
				  $select = Process::find($addconds)->limitPage($page, $pagesize);
				  break;
				case 'fileinfo':
				  $select = FileInfo::find($addconds)->limitPage($page, $pagesize);
				  break;
				case 'tcpconns':
				  $select = TCPConns::find($addconds)->limitPage($page, $pagesize);
				  break;
				case 'cmdinfo':
				  $select = CMDInfo::find($addconds)->limitPage($page, $pagesize);
				  break;
				case 'terminallog':
				  $select = Terminallog::find($addconds)->limitPage($page, $pagesize);
				  break;
				case 'reginfo':
				  $select = RegInfo::find($addconds)->limitPage($page, $pagesize);
				  break;
				case 'reginfo1':
				  $select = RegInfo::find($addconds)->limitPage($page, $pagesize);
				  break;
				default:
				  $select = OldAction::find($addconds)->limitPage($page, $pagesize);
				}

				//$select = Action::find($addconds)->limitPage($page, $pagesize);
				$this->_view['pager'] = $select->getPagination();
				$this->_view['group'] = $select->order("id desc")->getAll();

				if($this->_view['pager']['record_count']>0 && $page=='')
					$page=1;
				//echo $this->_view['pager']['record_count'];
				//$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'behaviorlog|index|','\')',5);
				$pagediv = new Helper_MyPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'index.php?controller=behaviorlog'.$sdstr.$edstr.'&page=','',5);
				$this->_view['pagestr']= $pagediv->show();

			}else{
				
				$pagesize = 10;
				$amac='';
				// 获取当前页数，通常为get方式参数
				$page = $this->_context->page;
				$this->_view['pageno']=$page;
				$this->_view['macs']=$this->_context->mac;
				if(isset($_POST['mac']) && $_POST['mac']!=''){
					$amac=' and macaddress = ?';
					$pmac=$_POST['mac'];
				}
				if($this->_context->mac!=''){
					$amac=' and macaddress = ?';
					$pmac=$this->_context->mac;
				}
				switch ($iftype)
				{
				case '':
				  $select = OldAction::find($addconds.$amac,$pmac)->limitPage($page, $pagesize);
				  break;
				case 'process':
				  $select = Process::find($addconds.$amac,$pmac)->limitPage($page, $pagesize);
				  break;
				case 'fileinfo':
				  $select = FileInfo::find($addconds.$amac,$pmac)->limitPage($page, $pagesize);
				  break;
				case 'tcpconns':
				  $select = TCPConns::find($addconds.$amac,$pmac)->limitPage($page, $pagesize);
				  break;
				case 'cmdinfo':
				  $select = CMDInfo::find($addconds.$amac,$pmac)->limitPage($page, $pagesize);
				  break;
				case 'terminallog':
				  $select = Terminallog::find($addconds.$amac,$pmac)->limitPage($page, $pagesize);
				  break;
				case 'reginfo':
				  $select = RegInfo::find($addconds)->limitPage($page, $pagesize);
				  break;
				case 'reginfo1':
				  $select = RegInfo::find($addconds)->limitPage($page, $pagesize);
				  break;
				default:
				  $select = OldAction::find($addconds.$amac,$pmac)->limitPage($page, $pagesize);
				}
				
				//$select = Action::find('macaddress = ? AND '.$addconds, $this->_context->mac)->limitPage($page, $pagesize);
				$this->_view['pager'] = $select->getPagination();
				$this->_view['group'] = $select->order("id desc")->getAll();

				if($this->_view['pager']['record_count']>0 && $page=='')
				$page=1;
				//echo $this->_view['pager']['record_count'];
				//$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'behaviorlog|index|','\')',5);

				$pagediv = new Helper_MyPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'index.php?controller=behaviorlog'.$sdstr.$edstr.'&mac='.$pmac.'&page=','',5);
				$this->_view['pagestr']= $pagediv->show();

			}
        }
        else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }

	function actionList(){
		
		$show_box['title'] = '行为日志首页';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1','查看'.$show_box['title'],'');

			//print_r($achosts);
			//$this->_view['groupc']= $allhave;
			// 设置页面列表数目
			$pagesize = 10;
			// 获取当前页数，通常为get方式参数
			$page = $this->_context->page;
			$this->_view['pageno']=$page;
			$select = Hostgroup::find()->limitPage($page, $pagesize);
			$this->_view['pager'] = $select->getPagination();
			$this->_view['group'] = $select->order("id desc")->getAll();
			$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
			if($this->_view['pager']['record_count']>0 && $page=='')
					$page=1;

			
			//echo $this->_view['pager']['record_count'];
			$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'behaviorlog|list|','\')',5);

			$this->_view['pagestr']= $pagediv->show();

		}
	}

	/*Host Manage*/
	function actionHostlist()
    {
		//判断是否需要统计今天的数据
		$istoday=false;
		//判断是否跨越历史数据
		$iscross=false;
		$isfirst=true;
		
		//时间筛选
			$addconds="date = '".date("Y-m-d")."'";
			$this->_view['startd']='';
			$this->_view['endd']='';
			if ($this->_context->isPOST())
			{
				if($_POST['startdate']==$_POST['enddate']){
					$endd=$this->my_date_add('d',$_POST['enddate'],1);

					if($_POST['startdate']==date("Y-m-d"))
						$istoday=true;

					$iscross=false;

				}else{
					$endd=$_POST['enddate'];
					
					if($_POST['startdate']==date("Y-m-d")){
						$istoday=true;
						$iscross=true;
					}else{
						$istoday=false;
						$iscross=true;
					}
					

				}
				$this->_view['startd']=$_POST['startdate'];
				$this->_view['endd']=$endd;
				$addconds="date >='".$_POST['startdate']."' and date<='".$endd."'";
				//echo $this->my_date_add('d',$_POST['enddate'],1);
				//echo $addconds;
				//dump($_POST);
			}

			if($this->_context->startd !='' && $this->_context->endd !=''){
				$this->_view['startd']=$this->_context->startd;
				$this->_view['endd']=$this->_context->endd;
				$addconds="date >='".$this->_context->startd."' and date<='".$this->_context->endd."'";
				$enddstr=$this->my_date_add('d',date("Y-m-d"),1);
				if($this->_context->startd==date("Y-m-d") && $this->_context->endd==$enddstr){
					$istoday=true;$iscross=false;
				}else{
					if($this->_context->startd==date("Y-m-d")){
						$istoday=true;$iscross=true;
					}else{
						$istoday=false;$iscross=true;
					}
				}
			}
		
		//dump($istoday);dump($iscross);
		//列出所有主机的MAC地址
			$table =QDB::getConn();
			$sql = "SELECT DISTINCT macaddress FROM `hosttable`";
			$handel =$table->execute($sql);
			$temp2 = $handel->fetchAll();
			$allhave2 = array();
			foreach ($temp2 as $s){
				$allhave2[$s['macaddress']]=array();
				//echo $s['groupid'];
			}

		//print_r($allhave2);

		if($istoday || $iscross || $isfirst){
				//默认列出今天的所有主机的行为日志的统计资料(总)
				$sql = "SELECT count( 1 ) AS macactions, `macaddress`,sum( `security` ) AS securitys FROM `action` WHERE ".$addconds." GROUP BY `macaddress`";
				$handel =$table->execute($sql);
				$temp3 = $handel->fetchAll();
				foreach ($temp3 as $s){
					$allhave2[$s['macaddress']]['actcounts']=$s['macactions'];
					$allhave2[$s['macaddress']]['alarms']=$s['securitys'];
					$allhave2[$s['macaddress']]['securitys']=$allhave2[$s['macaddress']]['actcounts']-$allhave2[$s['macaddress']]['alarms'];
					//echo $s['groupid'];
				}

				//print_r($allhave2);
			}

		$this->_view['hostc']= $allhave2;

		$show_box['title'] = '主机列表';
		// 设置页面列表数目
		//$pagesize = 10;
		// 获取当前页数，通常为get方式参数
		//$page = $this->_context->page;
		//echo $page;
		//echo $this->_context->id;
		$this->_view['gid']=$this->_context->id;
		//$this->_view['pageno']=$page;
		$select = Host::find('[group.groupid]= ?',$this->_context->id);
		//->limitPage($page, $pagesize);
		//$this->_view['pager'] = $select->getPagination();
		$this->_view['group'] = $select->order("id desc")->getAll();
		//$this->_view['countno'] = $this->_view['pager']['page_size']*$page+1;
		$this->_view['countno'] = 1;
		//if($this->_view['pager']['record_count']>0 && $page=='')
			//$page=1;

		//echo $this->_view['pager']['record_count'];
		//$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'behaviorlog|hostlist|','\')',5);
		//$this->_view['pagestr']= $pagediv->show();
    }

	/* ******************************************************************** */
    function actionFliter()
	{
		$show_box['title'] = '过滤查询';
		
		if ($this->_app->currentUserRoles())
        {
			Operate::everyOperate($_SESSION['acl_task_userdata']['account'],'','1',''.$show_box['title'],'');

			$this->_view['form'] = new Form_BeFliter(url('default::behaviorlog/index'));
		}
	}
    

	/* ******************************************************************** */
    function actionListcount()
    {
        //判断是否需要统计今天的数据
		$istoday=false;
		//判断是否跨越历史数据
		$iscross=false;

		$show_box['title'] = '行为日志列表(组管理员)';
        if ($this->_app->currentUserRoles())
        {
			
			//时间筛选
			$addconds="date = '".date("Y-m-d")."'";
			$this->_view['startd']='';
			$this->_view['endd']='';
			if ($this->_context->isPOST())
			{
				if($_POST['startdate']==$_POST['enddate']){
					$endd=$this->my_date_add('d',$_POST['enddate'],1);

					if($_POST['startdate']==date("Y-m-d"))
						$istoday=true;

					$iscross=false;

				}else{
					$endd=$_POST['enddate'];
					
					if($_POST['startdate']==date("Y-m-d")){
						$istoday=true;
						$iscross=true;
					}else{
						$istoday=false;
						$iscross=true;
					}
					

				}
				$this->_view['startd']=$_POST['startdate'];
				$this->_view['endd']=$endd;
				$addconds="date >='".$_POST['startdate']."' and date<='".$endd."'";
				//echo $this->my_date_add('d',$_POST['enddate'],1);
				//echo $addconds;
				//dump($_POST);
			}

			if($this->_context->startd !='' && $this->_context->endd !=''){
				$this->_view['startd']=$this->_context->startd;
				$this->_view['endd']=$this->_context->endd;
				$addconds="date >='".$this->_context->startd."' and date<='".$this->_context->endd."'";
				$enddstr=$this->my_date_add('d',date("Y-m-d"),1);
				if($this->_context->startd==date("Y-m-d") && $this->_context->endd==$enddstr){
					$istoday=true;$iscross=false;
				}else{
					if($this->_context->startd==date("Y-m-d")){
						$istoday=true;$iscross=true;
					}else{
						$istoday=false;$iscross=true;
					}
				}
			}


			$table =QDB::getConn();
			$sql = "SELECT DISTINCT groupid FROM `grouptohost`";
			$handel =$table->execute($sql);
			$temp = $handel->fetchAll();
			$allhave = array();
			foreach ($temp as $s){
				$allgroup = array();
				$allgroup['groupid']=$s['groupid'];
				$allhave[$s['groupid']]=$allgroup;
				//echo $s['groupid'];
			}

			$table =QDB::getConn();
			$sql = "SELECT count( 1 ) AS grouphosts, groupid FROM `grouptohost` GROUP BY `grouptohost`.groupid";
			$handel =$table->execute($sql);
			$temp1 = $handel->fetchAll();
			//$allhosts = array();
			foreach ($temp1 as $s){
				//$allgroup = array();
				//$allgroup['groupid']=$s['groupid'];
				$allhave[$s['groupid']]['hosts']=$s['grouphosts'];
				//echo $s['groupid'];
			}

			//列出所有主机的MAC地址
			//$table =QDB::getConn();
			$sql = "SELECT DISTINCT macaddress FROM `hosttable`";
			$handel =$table->execute($sql);
			$temp2 = $handel->fetchAll();
			$allhave2 = array();
			foreach ($temp2 as $s){
				$allhave2[$s['macaddress']]=array();
				//echo $s['groupid'];
			}
			if($istoday || $iscross){
				//默认列出今天的所有主机的行为日志的统计资料(总)
				$sql = "SELECT count( 1 ) AS macactions, `macaddress` FROM `action` WHERE ".$addconds." GROUP BY `macaddress`";
				$handel =$table->execute($sql);
				$temp3 = $handel->fetchAll();
				foreach ($temp3 as $s){
					$allhave2[$s['macaddress']]['actcounts']=$s['macactions'];
					//echo $s['groupid'];
				}

				//默认列出今天的所有主机的行为日志的统计资料(正常)
				$sql = "SELECT count( 1 ) AS macactions, `macaddress` FROM `action` WHERE ".$addconds." and security=0 GROUP BY `macaddress`";
				$handel =$table->execute($sql);
				$temp4 = $handel->fetchAll();
				foreach ($temp4 as $s){
					$allhave2[$s['macaddress']]['securitys']=$s['macactions'];
					//echo $s['groupid'];
				}
				//print_r($allhave2);
			}
			//echo $addconds;
			if($iscross){
				
				$table =QDB::getConn();
				//$sql = "SELECT sum( actiontotal ) AS ats, sum( actionalarm ) AS als, sum( eventtotal ) AS evs, sum( eventalarm ) AS els, `macaddress` FROM `statisticstable` WHERE ".$addconds." GROUP BY `macaddress`";
				$sql = "SELECT sum( actiontotal ) AS ats, sum( actionalarm ) AS als, `macaddress` FROM `statisticstable` WHERE ".$addconds." GROUP BY `macaddress`";
				$handel =$table->execute($sql);
				$temp5 = $handel->fetchAll();
				foreach ($temp5 as $s){
					if(isset($allhave2[$s['macaddress']]['actcounts']))
						$allhave2[$s['macaddress']]['actcounts']=$allhave2[$s['macaddress']]['actcounts']+$s['ats'];
					else
						$allhave2[$s['macaddress']]['actcounts']=$s['ats'];
					if(isset($allhave2[$s['macaddress']]['actcounts']))
						$allhave2[$s['macaddress']]['securitys']=$allhave2[$s['macaddress']]['actcounts']+($s['ats']-$s['als']);
					else
						$allhave2[$s['macaddress']]['securitys']=($s['ats']-$s['als']);
					//echo $s['groupid'];
				}
			}
			//print_r($allhave);
			$this->_view['groupc']= $allhave;
			$this->_view['groupd']= $allhave2;
			// 设置页面列表数目
			$pagesize = 10;
			// 获取当前页数，通常为get方式参数
			$page = $this->_context->page;
			$this->_view['pageno']=$page;
			$select = Hostgroup::find()->limitPage($page, $pagesize);
			$this->_view['pager'] = $select->getPagination();
			$this->_view['group'] = $select->order("id desc")->getAll();
			if($this->_view['pager']['record_count']>0 && $page=='')
					$page=1;
			//echo $this->_view['pager']['record_count'];
			$pagediv = new Helper_JsPager($this->_view['pager']['record_count'], $this->_view['pager']['page_size'], 9, $page, 'opgopage(\'behaviorlog|list|','\')',5);
			$this->_view['pagestr']= $pagediv->show();

        }
        else
        {
            // 未登录则转到登录页面
            return $this->_redirect(url('default/login'));
        }
    }

	function my_date_add($opt,$time,$num){
		$year = date('Y',strtotime($time));
		$month = date('m',strtotime($time));
		$day = date('d',strtotime($time));
		$last_day = date('t',strtotime($time));
		if($opt=='y'){
			$year = $year + $num;
		}else if($opt=='d'){
			$day = $day + $num;
		}else if($opt=='m'){
			$month = $month + $num;
			if($day == $last_day){//如果是最后一天的话
				$day = date('t',strtotime("{$year}-{$month}-01"));
			}
		} else {
			return $time;
		}
		return date("Y-m-d", mktime(0, 0, 0, $month, $day, $year));
	}

}